package com.atguigu.realtime.app;

import com.atguigu.realtime.util.FlinkSourceUtil;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.runtime.state.hashmap.HashMapStateBackend;
import org.apache.flink.streaming.api.CheckpointingMode;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.environment.CheckpointConfig;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;

import java.util.HashMap;
import java.util.Map;

/**
 * @Author lizhenchao@atguigu.cn
 * @Date 2021/11/23 9:01
 */
public abstract class BaseAppV2 {
    
    public void init(int port, int p, String ck, String groupId, String ... topics) {
        if (topics.length == 0) {
            throw new IllegalArgumentException("至少在参数末尾传入一个topic, 目前你一个都没有传");
        }
        
        System.setProperty("HADOOP_USER_NAME", "atguigu");
        Configuration conf = new Configuration();
        conf.setInteger("rest.port", port);
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(conf);
        env.setParallelism(p);
        
        env.setStateBackend(new HashMapStateBackend());
        env.getCheckpointConfig().setCheckpointStorage("hdfs://hadoop162:8020/realtime/" + ck);
        
        env.enableCheckpointing(3000, CheckpointingMode.EXACTLY_ONCE);
        
        env.getCheckpointConfig().setCheckpointTimeout(30000);
        env.getCheckpointConfig().setMaxConcurrentCheckpoints(1);
        env.getCheckpointConfig().setMinPauseBetweenCheckpoints(500);
        env.getCheckpointConfig()
            .enableExternalizedCheckpoints(CheckpointConfig.ExternalizedCheckpointCleanup.RETAIN_ON_CANCELLATION);
    
        HashMap<String, DataStreamSource<String>> streamMap = new HashMap<>();
        for (String topic : topics) {
            DataStreamSource<String> stream = env.addSource(FlinkSourceUtil.getKafkaSource(groupId, topic));
            streamMap.put(topic, stream);
        }
    
        run(env, streamMap);
        
        try {
            env.execute(ck);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    
    protected abstract void run(StreamExecutionEnvironment env, Map<String, DataStreamSource<String>> streamMap);
    
}
